<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import { createVNode, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

import {
  ColPage,
  ColVerticalPage,
  useVbenDrawer,
  useVbenModal,
} from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import {
  antDesignCaretRightOutlined,
  AntDesignOutLined,
  IconifyIcon,
} from '@vben/icons';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';
import { downloadFileFromUrl } from '@vben/utils';

import { useClipboard } from '@vueuse/core';
import { message, Modal } from 'ant-design-vue';

import { querySelectTableApi, querySelectTreeTableApi } from '#/api';
import { genConfigQueryOneApi } from '#/api/gen/config';
import {
  designPageEditApi,
  designPageQueryByIdApi,
} from '#/api/gen/designPage';
import {
  genCodeFrontEndPreviewCodeApi,
  genCodeFrontEndToProjectApi,
} from '#/api/gen/genCode';
import { genModelFieldsQueryModelFieldsApi } from '#/api/gen/modelFields';
import { genModelClassifyQueryClassifyAndModelApi } from '#/api/gen/modelType';
import { dictQueryListApi } from '#/api/system/dict';
import { getAntdMenuItem, queryDictOptionsApi, spliceUrlPrefix } from '#/utils';
import { ComponentList } from '#/views/onlineDesign/designModel/designModel.data';
import {
  colTableConfig,
  updateColTableConfig,
} from '#/views/onlineDesign/designPage/template/colTable/config';
import FormDrawerPage from '#/views/onlineDesign/designPage/template/colTable/form/FormDrawerPage.vue';
import FormModalPage from '#/views/onlineDesign/designPage/template/colTable/form/FormModalPage.vue';
import { sort } from '#/views/onlineDesign/designPage/template/methods/commonMethod';
import {
  defaultToGenerateForm,
  defaultToGenerateSelectForm,
} from '#/views/onlineDesign/designPage/template/methods/formMethod';
import { defaultToGenerateColumns } from '#/views/onlineDesign/designPage/template/methods/tableMethod';
import { tableConfig } from '#/views/onlineDesign/designPage/template/table/config';

const { copy } = useClipboard({ legacy: true });

const router = useRoute();

export interface RowType {
  id: string;
  createBy: string;
  createTime: string;
  updateBy: string;
  updateTime: string;
}

const { setTabTitle } = useTabs();

const modelCode = ref();
const pageId = ref();
const pageData = ref();
const activeKeyConfig = ref();
const activeKeySelectForm = ref();
const activeKeyColumns = ref();
const activeKeyForm = ref();
const layoutIndex = ref();
const modelFields = ref([]);
const previewCodeMap = ref();
const preActiveKey = ref('');
const dictList = ref([]);
const classifyModels = ref([]);
const leftModelFields = ref([]);

const allKey = '9999';
const typeData = reactive([]);
const selectedKeys = ref<string[]>([allKey]);
const openKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]);

// 弹窗数据
const popupParams = ref({
  title: '[模型名称]',
  modelFields: undefined,
  config: undefined,
});
setTabTitle(`Col_TABLE设计器`);
const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: FormDrawerPage,
});
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: FormModalPage,
});
const [PreviewCodeModal, previewCodeModalApi] = useVbenModal({
  title: '前端代码预览',
  onConfirm: () => previewCodeModalApi.close(),
  showCancelButton: false,
});

const formOptions: VbenFormProps = reactive({
  ...colTableConfig.selectForm.base,
  schema: [],
});

const gridOptions: VxeTableGridOptions<RowType> = reactive({
  height: 'auto',
  toolbarConfig: {
    slots: {
      buttons: 'toolbar-buttons',
    },
  },
  columns: [],
  data: [{ id: '1' }, { id: '2' }],
});
const [Grid, gridApi] = useVbenVxeGrid(reactive({ formOptions, gridOptions }));

// 监听参数变化
watch(
  () => router.params.data,
  async (val) => {
    if (val) {
      const split = val.split('-');
      modelCode.value = split[0];
      pageId.value = split[1];
      message.success(`modelCode:${router.params.data}`);
      // 加载页面信息
      pageData.value = await designPageQueryByIdApi({ id: pageId.value });
      if (pageData.value && pageData.value.pageParams) {
        await updateColTableConfig(JSON.parse(pageData.value.pageParams));
        await gridApi.grid.loadColumn(colTableConfig.table.columns);
      } else {
        // 加载字段数据
        modelFields.value = await genModelFieldsQueryModelFieldsApi({
          modelCode: modelCode.value,
        });
        popupParams.value.modelFields = modelFields.value;
        // 生成查询表单
        await defaultGenerateSelectForm(modelFields.value);
        // 生成表格项
        await defaultGenerateColumns(modelFields.value);
        // 生成表单
        await defaultGenerateForm(modelFields.value);
      }
    }
  },
  { immediate: true },
);

// 监听查询表单配置变化
watch(
  () => colTableConfig.selectForm.base,
  async (val) => {
    await gridApi.formApi.setState(val);
  },
  { deep: true },
);
// 监听查询表单参数变化
watch(
  () => colTableConfig.selectForm.options,
  async (val) => {
    // 筛选出isSelect为true的所有对象
    const selectedItems = val.filter((item) => item.extra.showSelect);
    await gridApi.formApi.setState({ schema: selectedItems });
  },
  { deep: true },
);

// 监听表格属性配置
watch(
  () => colTableConfig.table.columns,
  async (val) => {
    await gridApi.grid.loadColumn(val);
  },
  { deep: true },
);

// 监听表单布局
watch(
  () => colTableConfig.form.base.wrapperClass,
  async (val) => {
    // 处理 val 字符串，获取最后一个字符并转为数字
    const classes = val.trim().split(' ');
    if (classes.length === 0) {
      layoutIndex.value = 6;
      return;
    }
    const lastClass = classes[classes.length - 1];
    const lastChar = lastClass.charAt(lastClass.length - 1);
    // 尝试将最后一个字符转换为数字
    const lastCharAsNumber = Number.parseInt(lastChar, 10);
    layoutIndex.value = lastCharAsNumber || 6;
  },
  { immediate: true },
);

// 监听数据字典选择
watch(
  () => colTableConfig.colModel.type,
  async (val) => {
    if (val) {
      if (val === 'normal') {
        if (colTableConfig.colModel.mode === 'dict') {
          dictList.value = await dictQueryListApi();
        } else {
          classifyModels.value =
            await genModelClassifyQueryClassifyAndModelApi();
        }
      } else {
        classifyModels.value = await genModelClassifyQueryClassifyAndModelApi();
      }
    }
  },
  { immediate: true },
);

// 监听选择表
watch(
  () => colTableConfig.colModel.params.tableName,
  async (val) => {
    if (val) {
      leftModelFields.value = await genModelFieldsQueryModelFieldsApi({
        modelCode: val,
      });
    }
  },
  { immediate: false },
);

// 监听左侧是树还是平级
watch(
  () => colTableConfig.colModel.type,
  async (val) => {
    // 切换时，直接清空分类数据
    typeData.splice(0, typeData.length);
    if (val === 'tree') {
      await loadTree();
    } else {
      colTableConfig.colModel.mode === 'dict'
        ? await loadDict()
        : await loadDictTable();
    }
  },
  { immediate: true },
);

// 监听选择的是否字典还是表
watch(
  () => colTableConfig.colModel.mode,
  async (val) => {
    // 切换时，直接清空分类数据
    typeData.splice(0, typeData.length);
    val === 'dict' ? await loadDict() : await loadDictTable();
  },
);

// 监听左侧参数变化
watch(
  () => colTableConfig.colModel.params,
  async (val) => {
    if (colTableConfig.colModel.type === 'normal') {
      if (colTableConfig.colModel.mode === 'dict') {
        if (!val.dictCode) {
          message.error('请选择数据字典');
          return;
        }
        await loadDict();
      } else {
        if (!val.tableName) {
          message.error('请选择模型');
          return;
        }
        if (!val.labelField) {
          message.error('请选择模型展示字段');
          return;
        }
        if (!val.valueField) {
          message.error('请选择模型的值');
          return;
        }
        await loadDictTable();
      }
    } else {
      if (!val.tableName) {
        message.error('请选择模型');
        return;
      }
      if (!val.labelField) {
        message.error('请选择模型展示字段');
        return;
      }
      if (!val.valueField) {
        message.error('请选择模型的值');
        return;
      }
      await loadTree();
    }
  },
  { deep: true },
);

// 加载左侧数据字典
async function loadDict() {
  // 数据字典
  if (colTableConfig.colModel.params.dictCode) {
    const data = await queryDictOptionsApi({
      dictCode: colTableConfig.colModel.params.dictCode,
    });
    typeData.splice(0, typeData.length);
    typeData.push(getAntdMenuItem('全部', allKey));
    data.forEach((dict) => {
      typeData.push(getAntdMenuItem(dict.itemText, dict.itemVal));
    });
  }
}
// 加载表数据
async function loadDictTable() {
  if (
    colTableConfig.colModel.params.tableName &&
    colTableConfig.colModel.params.labelField &&
    colTableConfig.colModel.params.valueField
  ) {
    const data = await querySelectTableApi({
      tableName: colTableConfig.colModel.params.tableName,
      labelField: colTableConfig.colModel.params.labelField,
      valueField: colTableConfig.colModel.params.valueField,
      sqlSelect: 'del_flag = 0',
    });
    typeData.splice(0, typeData.length);
    typeData.push(getAntdMenuItem('全部', allKey));
    data.forEach((dict) => {
      typeData.push(getAntdMenuItem(dict.label, dict.value));
    });
  }
}

// 加载左侧树数据
async function loadTree() {
  if (
    colTableConfig.colModel.params.tableName &&
    colTableConfig.colModel.params.labelField &&
    colTableConfig.colModel.params.valueField
  ) {
    const data = await querySelectTreeTableApi({
      tableName: colTableConfig.colModel.params.tableName,
      labelField: colTableConfig.colModel.params.labelField,
      valueField: colTableConfig.colModel.params.valueField,
      sqlSelect: 'del_flag = 0',
    });
    typeData.splice(0, typeData.length, ...data);
  }
}

// 默认生成查询表单
async function defaultGenerateSelectForm(fields: Array) {
  colTableConfig.selectForm.options = await defaultToGenerateSelectForm(
    fields,
    colTableConfig,
  );
  await gridApi.formApi.setState({ schema: colTableConfig.selectForm.options });
}
// 默认生成表格项
async function defaultGenerateColumns(fields: Array) {
  colTableConfig.table.columns = await defaultToGenerateColumns(
    fields,
    0,
    colTableConfig,
  );
  await sort(colTableConfig.table.columns);
  await gridApi.grid.loadColumn(colTableConfig.table.columns);
}
// 默认生成表单
async function defaultGenerateForm(fields: Array) {
  colTableConfig.form.options = await defaultToGenerateForm(
    fields,
    colTableConfig,
  );
}
// 更新排序
async function updateSort() {
  await sort(colTableConfig.table.columns);
  await gridApi.grid.loadColumn(colTableConfig.table.columns);
  message.success('排序更新成功');
}
// 保存配置
async function saveConfig() {
  const msg = await designPageEditApi({
    id: pageId.value,
    pageParams: JSON.stringify(colTableConfig),
  });
  message.success(msg);
  // console.log('保存配置：', colTableConfig);
}
// 预览代码
async function openPreviewCode() {
  const config = await loadConfig();
  if (config.frontEndPath) {
    previewCodeMap.value = await genCodeFrontEndPreviewCodeApi(pageId.value);
    preActiveKey.value = previewCodeMap.value[0]?.key;
    previewCodeModalApi.open();
  } else {
    Modal.confirm({
      title: `系统提示`,
      okText: '前往配置',
      content: createVNode(
        'div',
        { style: 'color:red;' },
        '请先完成前端目录信息的配置!',
      ),
      async onOk() {
        await router.push({ name: 'Online/config' });
      },
      class: 'test',
    });
  }
}
/**
 * 生成代码
 * @param index 0生成到项目 1下载
 */
async function generateCodeProject(index) {
  if (index === 1) {
    message.warn('目前无法下载代码文件');
    return;
  }
  // 如果是生产环境不允许
  const env = import.meta.env.PROD ? 'prod' : 'dev';
  if (env === 'prod') {
    message.warn('生产环境下无法生成代码To项目');
    return;
  }
  const config = await loadConfig();
  if (config.frontEndPath && config.frontProjectPath) {
    const msg = await genCodeFrontEndToProjectApi(pageId.value);
    message.success(msg);
  } else {
    Modal.confirm({
      title: `系统提示`,
      okText: '前往配置',
      content: createVNode(
        'div',
        { style: 'color:red;' },
        '请先完成前端目录信息的配置!',
      ),
      async onOk() {
        await router.push({ name: 'Online/config' });
      },
      class: 'test',
    });
  }
}
// 是否配置了代码生成必须参数
async function loadConfig() {
  return await genConfigQueryOneApi();
}
// 左侧点击事件
async function handleType(e) {
  selectedKeys.value[0] = e?.key;
  message.warn(`点击的数据:${selectedKeys.value[0]},注意：预览列表不会联动`);
}
// 左侧展开收起
// function handlerType(type) {
//   const allKeys = getAllNodeKeys(typeData);
//   type === 1 ? (expandedKeys.value = []) : (expandedKeys.value = allKeys);
// }
// 树点击
async function onTreeTypeSelect(keys) {
  selectedKeys.value[0] = keys[0];
  message.warn(`点击的数据:${selectedKeys.value[0]},注意：预览列表不会联动`);
}
</script>

<template>
  <ColPage
    v-bind="{
      resizable: true,
      splitLine: true,
      splitHandle: true,
      leftWidth: 82,
      leftMaxWidth: 82,
      leftMinWidth: 82,
      rightWidth: 18,
      rightMinWidth: 18,
      rightMaxWidth: 18,
    }"
    auto-content-height
  >
    <PreviewCodeModal class="w-[80%]">
      <a-tabs v-model:active-key="preActiveKey" tab-position="left">
        <a-tab-pane
          v-for="item in previewCodeMap"
          :key="item?.key"
          :tab="item?.key"
        >
          <div style="overflow: auto">
            <a-button
              style="float: right"
              type="link"
              @click="copy(item?.content)"
            >
              复制
            </a-button>
            <pre v-if="item?.content">{{ item?.content }}</pre>
          </div>
        </a-tab-pane>
      </a-tabs>
    </PreviewCodeModal>
    <FormDrawer class="w-[50%]" />
    <FormModal class="w-[50%]" />
    <template #left>
      <ColPage v-bind="colTableConfig.col" auto-content-height>
        <template #left="{ isCollapsed, expand }">
          <div v-if="isCollapsed" @click="expand">
            <a-tooltip title="点击展开左侧">
              <a-button shape="circle" type="primary">
                <template #icon>
                  <IconifyIcon class="text-2xl" icon="bi:arrow-right" />
                </template>
              </a-button>
            </a-tooltip>
          </div>
          <div
            v-else
            class="border-border bg-card mr-2 h-full rounded-[var(--radius)] border p-2"
          >
            <template v-if="colTableConfig.colModel.type === 'normal'">
              <template v-if="colTableConfig.colModel.mode === 'dict'">
                <ColVerticalPage :title="colTableConfig.colModel.leftTitle">
                  <a-menu
                    v-if="typeData.length > 0"
                    mode="inline"
                    :items="typeData"
                    v-model:selected-keys="selectedKeys"
                    v-model:open-keys="openKeys"
                    @click="handleType"
                  />
                  <div v-else style="color: red">请选择字典数据</div>
                </ColVerticalPage>
              </template>
              <template
                v-else-if="colTableConfig.colModel.mode === 'dictTable'"
              >
                <ColVerticalPage>
                  <template #header>
                    <div class="flex items-center">
                      <div class="mr-2">
                        {{ colTableConfig.colModel.leftTitle }}
                      </div>
                      <div>
                        <a-input-search
                          :placeholder="`请输入${colTableConfig.colModel.leftTitle}`"
                          enter-button
                          allow-clear
                          size="small"
                        />
                      </div>
                    </div>
                  </template>
                  <a-menu
                    v-if="typeData.length > 0"
                    mode="inline"
                    :items="typeData"
                    v-model:selected-keys="selectedKeys"
                    v-model:open-keys="openKeys"
                    @click="handleType"
                  />
                  <div v-else style="color: red">请选择表数据</div>
                </ColVerticalPage>
              </template>
            </template>
            <template v-else>
              <ColVerticalPage>
                <template #header>
                  <div class="flex items-center">
                    <div class="mr-2">
                      {{ colTableConfig.colModel.leftTitle }}
                    </div>
                    <div>
                      <a-input-search
                        :placeholder="`请输入${colTableConfig.colModel.leftTitle}`"
                        enter-button
                        allow-clear
                        size="small"
                      />
                    </div>
                    <!--                    <a-dropdown>-->
                    <!--                      <AntDesignOutLined class="size-4" />-->
                    <!--                      <template #overlay>-->
                    <!--                        <a-menu>-->
                    <!--                          <a-menu-item @click="handlerType(0)">-->
                    <!--                            展开全部-->
                    <!--                          </a-menu-item>-->
                    <!--                          <a-menu-item @click="handlerType(1)">-->
                    <!--                            折叠全部-->
                    <!--                          </a-menu-item>-->
                    <!--                        </a-menu>-->
                    <!--                      </template>-->
                    <!--                    </a-dropdown>-->
                  </div>
                </template>
                <a-tree
                  :show-line="true"
                  :tree-data="typeData"
                  :field-names="{ title: 'name', key: 'id' }"
                  @select="onTreeTypeSelect"
                  v-model:expanded-keys="expandedKeys"
                  v-model:selected-keys="selectedKeys"
                />
              </ColVerticalPage>
            </template>
          </div>
        </template>
        <div
          class="border-border bg-card ml-2 h-full rounded-[var(--radius)] border p-2"
        >
          <Grid>
            <!-- 左侧按钮 -->
            <template
              #toolbar-buttons
              v-if="colTableConfig.table.actionBtn.buttons"
            >
              <a-button
                v-for="(btn, index) in colTableConfig.table.actionBtn.buttons"
                :key="index"
                :class="btn.class"
                :type="btn.type"
                :danger="btn.danger"
                :size="btn.size"
                @click="
                  btn.handlerFun(
                    formModalApi,
                    formDrawerApi,
                    popupParams,
                    colTableConfig,
                  )
                "
              >
                {{ btn.text }}
              </a-button>
            </template>
            <!-- 右侧按钮 -->
            <template
              #toolbar-tools
              v-if="colTableConfig.table.actionBtn.tools"
            >
              <a-button
                v-for="(btn, index) in colTableConfig.table.actionBtn.tools"
                :key="index"
                :class="btn.class"
                :type="btn.type"
                :danger="btn.danger"
                :size="btn.size"
                @click="btn.handlerFun"
              >
                {{ btn.text }}
              </a-button>
            </template>
            <!-- 操作按钮 -->
            <template
              #action="{ row }"
              v-if="colTableConfig.table.actionBtn.action"
            >
              <template
                v-for="(btn, index) in tableConfig.table.actionBtn.action"
              >
                <template v-if="btn?.handlerWay">
                  <template v-if="btn?.handlerWay === 'pop'">
                    <a-popconfirm
                      :key="index"
                      cancel-text="再想想"
                      title="您确定要删除吗?"
                      @confirm="btn.handlerFun(row)"
                    >
                      <a-button
                        :class="btn.class"
                        :type="btn.type"
                        :danger="btn.danger"
                        :size="btn.size"
                      >
                        {{ btn.text }}
                      </a-button>
                    </a-popconfirm>
                  </template>
                </template>
                <template v-else>
                  <a-button
                    :key="index"
                    :class="btn.class"
                    :type="btn.type"
                    :danger="btn.danger"
                    :size="btn.size"
                    @click="btn.handlerFun(row)"
                  >
                    {{ btn.text }}
                  </a-button>
                </template>
              </template>
            </template>
          </Grid>
        </div>
      </ColPage>
    </template>
    <div
      class="border-border bg-card ml-2 h-full rounded-[var(--radius)] border p-2"
      style="overflow: auto"
    >
      <div class="mb-2 flex justify-between">
        <a-dropdown-button type="primary" @click="saveConfig">
          保存配置
          <template #overlay>
            <a-menu>
              <a-menu-item key="1"> 重载所有配置 </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown-button>
        <a-dropdown-button type="primary" @click="openPreviewCode">
          预览代码
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="generateCodeProject(0)">
                前端代码生成->项目
              </a-menu-item>
              <a-menu-item
                key="2"
                @click="
                  downloadFileFromUrl({
                    source: spliceUrlPrefix(
                      `/gen/code/downloadFrontCode?pageId=${pageId}`,
                    ),
                    target: '_self',
                  })
                "
              >
                前端代码下载->Zip
              </a-menu-item>
            </a-menu>
          </template>
          <template #icon><AntDesignOutLined /></template>
        </a-dropdown-button>
      </div>
      <a-collapse v-model:active-key="activeKeyConfig" accordion>
        <a-collapse-panel key="1" header="左侧分类配置">
          <div class="mb-2">
            <span>左侧宽度：</span>
            <a-input-number
              addon-after="%"
              class="w-full"
              v-model:value="colTableConfig.col.leftWidth"
            />
          </div>
          <div class="mb-2">
            <span>右侧宽度：</span>
            <a-input-number
              addon-after="%"
              class="w-full"
              v-model:value="colTableConfig.col.rightWidth"
            />
          </div>
          <div class="mb-2">
            <span>分类名称：</span>
            <a-input
              class="w-full"
              v-model:value="colTableConfig.colModel.leftTitle"
            />
          </div>
          <div class="mb-2">
            <span>是否搜索：</span>
            <a-checkbox
              :disabled="true"
              v-model:checked="colTableConfig.colModel.showSelect"
            />
          </div>
          <div class="mb-2">
            <span>主模型关联字段：</span>
            <a-select
              class="w-full"
              v-model:value="colTableConfig.colModel.mainModelField"
            >
              <a-select-option
                v-for="(item, index) in modelFields"
                :key="index"
                :value="item.fieldName"
              >
                {{ item.fieldAnnotation }}
              </a-select-option>
            </a-select>
          </div>
          <div class="mb-2">
            <span>左侧数据类型：</span>
            <a-radio-group
              v-model:value="colTableConfig.colModel.type"
              button-style="solid"
              size="small"
            >
              <a-radio-button value="normal">平级分类</a-radio-button>
              <a-radio-button value="tree">树分类</a-radio-button>
            </a-radio-group>
          </div>
          <template v-if="colTableConfig.colModel.type === 'normal'">
            <div class="mb-2">
              <span>左侧数据来源：</span>
              <a-radio-group
                v-model:value="colTableConfig.colModel.mode"
                button-style="solid"
                size="small"
              >
                <a-radio-button value="dict">数据字典</a-radio-button>
                <a-radio-button value="dictTable">表数据</a-radio-button>
              </a-radio-group>
            </div>
            <div class="mb-2" v-if="colTableConfig.colModel.mode === 'dict'">
              <span>选择字典：</span>
              <a-select
                class="w-full"
                v-model:value="colTableConfig.colModel.params.dictCode"
              >
                <a-select-option
                  v-for="(item, index) in dictList"
                  :key="index"
                  :value="item.dictCode"
                >
                  {{ item.dictName }}
                </a-select-option>
              </a-select>
            </div>
            <template v-else>
              <div class="mb-2">
                <span>选择模型：</span>
                <a-select
                  class="w-full"
                  v-model:value="colTableConfig.colModel.params.tableName"
                >
                  <a-select-opt-group
                    v-for="(item, index) in classifyModels"
                    :key="index"
                    :label="item?.name"
                  >
                    <a-select-option
                      v-for="(child, childIndex) in item?.models"
                      :key="childIndex"
                      :value="child?.modelCode"
                    >
                      {{ child?.modelName }}
                    </a-select-option>
                  </a-select-opt-group>
                </a-select>
              </div>
              <div class="mb-2">
                <span>选择模型展示字段：</span>
                <a-select
                  class="w-full"
                  v-model:value="colTableConfig.colModel.params.labelField"
                >
                  <a-select-option
                    v-for="(item, index) in leftModelFields"
                    :key="index"
                    :value="item.fieldName"
                  >
                    {{ item.fieldAnnotation }}
                  </a-select-option>
                </a-select>
              </div>
              <div class="mb-2">
                <span>选择模型关联字段：</span>
                <a-select
                  class="w-full"
                  v-model:value="colTableConfig.colModel.params.valueField"
                >
                  <a-select-option
                    v-for="(item, index) in leftModelFields"
                    :key="index"
                    :value="item.fieldName"
                  >
                    {{ item.fieldAnnotation }}
                  </a-select-option>
                </a-select>
              </div>
            </template>
          </template>
          <template v-else>
            <div class="mb-2">
              <span>选择模型：</span>
              <a-select
                class="w-full"
                v-model:value="colTableConfig.colModel.params.tableName"
              >
                <a-select-opt-group
                  v-for="(item, index) in classifyModels"
                  :key="index"
                  :label="item?.name"
                >
                  <a-select-option
                    v-for="(child, childIndex) in item?.models"
                    :key="childIndex"
                    :value="child?.modelCode"
                  >
                    {{ child?.modelName }}
                  </a-select-option>
                </a-select-opt-group>
              </a-select>
            </div>
            <div class="mb-2">
              <span>选择模型展示字段：</span>
              <a-select
                class="w-full"
                v-model:value="colTableConfig.colModel.params.labelField"
              >
                <a-select-option
                  v-for="(item, index) in leftModelFields"
                  :key="index"
                  :value="item.fieldName"
                >
                  {{ item.fieldAnnotation }}
                </a-select-option>
              </a-select>
            </div>
            <div class="mb-2">
              <span>选择模型关联字段：</span>
              <a-select
                class="w-full"
                v-model:value="colTableConfig.colModel.params.valueField"
              >
                <a-select-option
                  v-for="(item, index) in leftModelFields"
                  :key="index"
                  :value="item.fieldName"
                >
                  {{ item.fieldAnnotation }}
                </a-select-option>
              </a-select>
            </div>
          </template>
        </a-collapse-panel>
        <a-collapse-panel key="2" header="查询表单配置">
          <div class="mb-2">
            <span>显示查询(无法实时预览)：</span>
            <a-checkbox
              v-model:checked="colTableConfig.selectForm.extra.showSelect"
            />
          </div>
          <template v-if="colTableConfig.selectForm.extra.showSelect">
            <div class="mb-2">
              <span>表单项布局：</span>
              <a-radio-group
                v-model:value="colTableConfig.selectForm.base.layout"
                button-style="solid"
                size="small"
              >
                <a-radio-button value="horizontal">水平</a-radio-button>
                <a-radio-button value="vertical">垂直</a-radio-button>
              </a-radio-group>
            </div>
            <div class="mb-2">
              <span>表单栅格布局：</span>
              <a-radio-group
                v-model:value="colTableConfig.selectForm.base.wrapperClass"
                button-style="solid"
                size="small"
              >
                <a-radio-button
                  value="grid-cols-1 md:grid-cols-2 lg:grid-cols-1"
                >
                  1
                </a-radio-button>
                <a-radio-button
                  value="grid-cols-1 md:grid-cols-2 lg:grid-cols-2"
                >
                  2
                </a-radio-button>
                <a-radio-button
                  value="grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
                >
                  3
                </a-radio-button>
                <a-radio-button
                  value="grid-cols-1 md:grid-cols-2 lg:grid-cols-4"
                >
                  4
                </a-radio-button>
                <a-radio-button
                  value="grid-cols-1 md:grid-cols-2 lg:grid-cols-5"
                >
                  5
                </a-radio-button>
                <a-radio-button
                  value="grid-cols-1 md:grid-cols-2 lg:grid-cols-6"
                >
                  6
                </a-radio-button>
              </a-radio-group>
            </div>
            <div class="mb-2">
              <span>显示展开/折叠：</span>
              <a-checkbox
                v-model:checked="
                  colTableConfig.selectForm.base.showCollapseButton
                "
              />
            </div>
            <div class="mb-2">
              <span>默认操作按钮：</span>
              <a-checkbox
                v-model:checked="
                  colTableConfig.selectForm.base.showDefaultActions
                "
              />
            </div>
            <div class="mb-2">
              <span>字段值改变时提交表单：</span>
              <a-checkbox
                v-model:checked="colTableConfig.selectForm.base.submitOnChange"
              />
            </div>
            <div class="mb-2">
              <span>回车时提交表单：</span>
              <a-checkbox
                v-model:checked="colTableConfig.selectForm.base.submitOnEnter"
              />
            </div>
            <div class="mb-2">
              <span>Label显示冒号：</span>
              <a-checkbox
                v-model:checked="
                  colTableConfig.selectForm.base.commonConfig.colon
                "
              />
            </div>
            <div class="mb-2">
              <span>表单项的label宽度：</span>
              <a-input-number
                class="w-full"
                v-model:value="
                  colTableConfig.selectForm.base.commonConfig.labelWidth
                "
              />
            </div>
            <a-divider>字段查询配置</a-divider>
            <a-collapse
              v-model:active-key="activeKeySelectForm"
              accordion
              class="w-full"
            >
              <template #expandIcon="{ isActive }">
                <antDesignCaretRightOutlined :rotate="isActive ? 90 : 0" />
              </template>
              <a-collapse-panel
                v-for="option in colTableConfig.selectForm.options"
                :key="option.fieldName"
                :header="option.label"
              >
                <div>
                  <div class="mb-2">
                    <span>查询：</span>
                    <a-checkbox v-model:checked="option.extra.showSelect" />
                  </div>
                  <div class="mb-2">
                    <span>帮助信息?：</span>
                    <a-input class="w-full" v-model:value="option.help" />
                  </div>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </template>
        </a-collapse-panel>
        <a-collapse-panel key="3" header="操作按钮">
          <a-button type="primary" size="small"> 添加操作按钮 </a-button>
          <div class="mt-1" style="color: #909399">
            <div>
              <span>列表左上区:</span>
              <div
                v-if="colTableConfig.table.actionBtn.buttons"
                class="pb-2 pt-2"
              >
                <a-button
                  v-for="(btn, index) in colTableConfig.table.actionBtn.buttons"
                  :key="index"
                  :class="btn.class"
                  :type="btn.type"
                  :danger="btn.danger"
                  size="small"
                >
                  {{ btn.text }}
                </a-button>
              </div>
            </div>
            <div>
              <span>列表右上区:</span>
              <div
                v-if="colTableConfig.table.actionBtn.tools"
                class="pb-2 pt-2"
              >
                <a-button
                  v-for="(btn, index) in colTableConfig.table.actionBtn.tools"
                  :key="index"
                  :class="btn.class"
                  :type="btn.type"
                  :danger="btn.danger"
                  size="small"
                >
                  {{ btn.text }}
                </a-button>
              </div>
            </div>
            <div>
              <span>行操作区:</span>
              <div
                v-if="colTableConfig.table.actionBtn.action"
                class="pb-2 pt-2"
              >
                <a-button
                  v-for="(btn, index) in colTableConfig.table.actionBtn.action"
                  :key="index"
                  :class="btn.class"
                  :type="btn.type"
                  :danger="btn.danger"
                  size="small"
                >
                  {{ btn.text }}
                </a-button>
              </div>
            </div>
          </div>
        </a-collapse-panel>
        <a-collapse-panel key="4" header="表格配置">
          <div class="mb-2">
            <span>选择列(无法实时预览)：</span>
            <a-checkbox
              v-model:checked="colTableConfig.table.extra.showChoose"
            />
          </div>
          <div class="mb-2">
            <span>序号(无法实时预览)：</span>
            <a-checkbox
              v-model:checked="colTableConfig.table.extra.showSerialNumber"
            />
          </div>
          <a-divider>字段配置</a-divider>
          <a-button
            class="mb-2"
            type="primary"
            size="small"
            @click="updateSort"
          >
            更新排序
          </a-button>
          <a-collapse v-model:active-key="activeKeyColumns">
            <template #expandIcon="{ isActive }">
              <antDesignCaretRightOutlined :rotate="isActive ? 90 : 0" />
            </template>
            <a-collapse-panel
              v-for="column in colTableConfig.table.columns"
              :key="column.field"
              :header="column.title"
            >
              <div>
                <div class="mb-2">
                  <span>对齐方式：</span>
                  <a-radio-group
                    v-model:value="column.align"
                    button-style="solid"
                    size="small"
                    :disabled="
                      (column.type && column.type === 'seq') ||
                      column.type === 'checkbox'
                    "
                  >
                    <a-radio-button value="left">左对齐</a-radio-button>
                    <a-radio-button value="center">居中对齐</a-radio-button>
                    <a-radio-button value="right">右对齐</a-radio-button>
                  </a-radio-group>
                </div>
                <div class="mb-2">
                  <span>固定列：</span>
                  <a-radio-group
                    v-model:value="column.fixed"
                    button-style="solid"
                    size="small"
                    :disabled="
                      (column.type && column.type === 'seq') ||
                      column.type === 'checkbox'
                    "
                  >
                    <a-radio-button value="left">冻结左侧</a-radio-button>
                    <a-radio-button value="right">冻结右侧</a-radio-button>
                  </a-radio-group>
                </div>
                <div class="mb-2">
                  <span>显示：</span>
                  <a-checkbox
                    v-model:checked="column.visible"
                    :disabled="
                      (column.type && column.type === 'seq') ||
                      column.type === 'checkbox'
                    "
                  />
                </div>
                <div class="mb-2">
                  <span>列宽：</span>
                  <a-input
                    class="w-full"
                    v-model:value="column.width"
                    :disabled="
                      (column.type && column.type === 'seq') ||
                      column.type === 'checkbox'
                    "
                  />
                </div>
                <div class="mb-2">
                  <span>顺序：</span>
                  <a-input
                    class="w-full"
                    v-model:value="column.extra.sequence"
                    :disabled="
                      (column.type && column.type === 'seq') ||
                      column.type === 'checkbox'
                    "
                  />
                </div>
                <div class="mb-2">
                  <span>列展现：</span>
                  <a-radio-group
                    v-model:value="column.showType"
                    button-style="solid"
                    size="small"
                    :disabled="
                      (column.type && column.type === 'seq') ||
                      column.type === 'checkbox'
                    "
                  >
                    <a-radio-button value="text">文本</a-radio-button>
                    <a-radio-button value="dict">数据字典</a-radio-button>
                    <a-radio-button value="dictTable">表字典</a-radio-button>
                    <a-radio-button value="image">图片</a-radio-button>
                    <a-radio-button value="files">文件</a-radio-button>
                    <a-radio-button value="link">按钮</a-radio-button>
                    <a-radio-button value="html">HTML</a-radio-button>
                  </a-radio-group>
                </div>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </a-collapse-panel>
        <a-collapse-panel key="5" header="表单配置">
          <div class="mb-2">
            <span>表单打开类型：</span>
            <a-radio-group
              v-model:value="colTableConfig.form.extra.openFormType"
              button-style="solid"
              size="small"
            >
              <a-radio-button value="modal">模态框</a-radio-button>
              <a-radio-button value="drawer">抽屉</a-radio-button>
            </a-radio-group>
          </div>
          <div class="mb-2">
            <span>容器宽度(无法实时预览)：</span>
            <a-input
              class="w-full"
              addon-after="%"
              v-model:value="colTableConfig.form.extra.openFormWidth"
            />
          </div>
          <div class="mb-2">
            <span>表单项布局：</span>
            <a-radio-group
              v-model:value="colTableConfig.form.base.layout"
              button-style="solid"
              size="small"
            >
              <a-radio-button value="horizontal">水平</a-radio-button>
              <a-radio-button value="vertical">垂直</a-radio-button>
            </a-radio-group>
          </div>
          <div class="mb-2">
            <span>表单栅格布局：</span>
            <a-radio-group
              v-model:value="colTableConfig.form.base.wrapperClass"
              button-style="solid"
              size="small"
            >
              <a-radio-button value="grid-cols-1 md:grid-cols-2 lg:grid-cols-1">
                1
              </a-radio-button>
              <a-radio-button value="grid-cols-1 md:grid-cols-2 lg:grid-cols-2">
                2
              </a-radio-button>
              <a-radio-button value="grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
                3
              </a-radio-button>
              <a-radio-button value="grid-cols-1 md:grid-cols-2 lg:grid-cols-4">
                4
              </a-radio-button>
              <a-radio-button value="grid-cols-1 md:grid-cols-2 lg:grid-cols-5">
                5
              </a-radio-button>
              <a-radio-button value="grid-cols-1 md:grid-cols-2 lg:grid-cols-6">
                6
              </a-radio-button>
            </a-radio-group>
          </div>
          <div class="mb-2">
            <span>表单默认按钮：</span>
            <a-checkbox
              :disabled="true"
              v-model:checked="colTableConfig.form.base.showDefaultActions"
            />
          </div>
          <div class="mb-2">
            <span>Label显示冒号：</span>
            <a-checkbox
              v-model:checked="colTableConfig.form.base.commonConfig.colon"
            />
          </div>
          <div class="mb-2">
            <span>表单项的label宽度：</span>
            <a-input-number
              class="w-full"
              v-model:value="colTableConfig.form.base.commonConfig.labelWidth"
            />
          </div>
          <a-divider>表单字段配置</a-divider>
          <div class="mb-2">
            <a-collapse v-model:active-key="activeKeyForm" accordion>
              <template #expandIcon="{ isActive }">
                <antDesignCaretRightOutlined :rotate="isActive ? 90 : 0" />
              </template>
              <a-collapse-panel
                v-for="(option, index) in colTableConfig.form.options"
                :key="index"
                :header="option.label"
              >
                <div>
                  <div class="mb-2">
                    <span>显示：</span>
                    <a-checkbox v-model:checked="option.extra.showSelect" />
                  </div>
                  <div class="mb-2">
                    <span>组件类型：</span>
                    <a-select
                      v-model:value="option.component"
                      size="small"
                      class="w-full"
                      :disabled="true"
                    >
                      <a-select-option
                        v-for="(item, index) in ComponentList"
                        :key="index"
                        :value="item.value"
                      >
                        {{ item.label }}
                      </a-select-option>
                    </a-select>
                  </div>
                  <div class="mb-2">
                    <span>顺序：</span>
                    <a-input class="w-full" v-model:value="option.sequence" />
                  </div>
                  <div class="mb-2">
                    <span>帮助信息?：</span>
                    <a-input class="w-full" v-model:value="option.help" />
                  </div>
                  <div class="mb-2">
                    <span>组件默认值：</span>
                    <a-input
                      v-if="option.extra.fieldPackagePath.includes('String')"
                      class="w-full"
                      v-model:value="option.defaultValue"
                    />
                    <a-input-number
                      v-else
                      class="w-full"
                      v-model:value="option.defaultValue"
                    />
                  </div>
                  <div class="mb-2">
                    <span>后缀：</span>
                    <a-input class="w-full" v-model:value="option.suffix" />
                  </div>
                  <div class="mb-2">
                    <span>表单项布局：</span>
                    <a-radio-group
                      v-model:value="option.formItemClass"
                      button-style="solid"
                      size="small"
                    >
                      <a-radio-button
                        :disabled="layoutIndex < 1"
                        value="col-span-1"
                      >
                        1
                      </a-radio-button>
                      <a-radio-button
                        :disabled="layoutIndex < 2"
                        value="col-span-2"
                      >
                        2
                      </a-radio-button>
                      <a-radio-button
                        :disabled="layoutIndex < 3"
                        value="col-span-3"
                      >
                        3
                      </a-radio-button>
                      <a-radio-button
                        :disabled="layoutIndex < 4"
                        value="col-span-4"
                      >
                        4
                      </a-radio-button>
                      <a-radio-button
                        :disabled="layoutIndex < 5"
                        value="col-span-5"
                      >
                        5
                      </a-radio-button>
                      <a-radio-button
                        :disabled="layoutIndex < 6"
                        value="col-span-6"
                      >
                        6
                      </a-radio-button>
                    </a-radio-group>
                  </div>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </ColPage>
</template>

<style scoped>
/deep/ .ant-collapse-content-box {
  padding: 6px !important;
}
</style>
